import csv
import os

from util import logger


class XlsWrite:
    def __init__ (self, file_path):
        self.file_path = file_path
        self.count = 0
        self.result_headers = [('评论时间', 'created_at'),
                               ('评论ID', 'created_id'),
                               ('评论内容', 'comment_text'),
                               ('评论者id', 'comment_user_id'),
                               ('评论者昵称', 'comment_user_name'),
                               ('评论者个人介绍', 'description'),
                               ('评论者性别', 'gender'),
                               ('评论者关注数', 'follow_count'),
                               ('评论者粉丝数', 'followers_count'),
                               ('评论点赞数', 'like_count')]
        try:
            with open(self.file_path + str(self.count) + '.csv', 'a', encoding='utf-8-sig',
                      newline='') as f:
                writer = csv.writer(f)
                writer.writerows([[kv[0] for kv in self.result_headers]])
        except Exception as e:
            logger.exception(e)
            print('创建或打开文件失败')

    def write_user(self, user):
        self.user = user

    def write_weibo(self, weibos):
        """将爬取的信息写入csv文件"""
        try:
            while os.path.exists(self.file_path + str(self.count) + '.csv'):
                # 如果文件已存在，递增计数器并更新文件名
                self.count += 1
            with open(self.file_path + str(self.count) + '.csv', 'a', encoding='utf-8-sig',
                      newline='') as f:
                for comment in weibos:
                    writer = csv.writer(f)
                    writer.writerow(vars(comment).values())
                print('写入完毕=============================')
                # writer.writerows(result_data)
            logger.info(u'%d条微博写入csv文件完毕，保存路径：%s', len(weibos), self.file_path + str(self.count) + '.csv')
            self.count += 1  # 每写入一次+1
        except Exception as e:
            logger.exception(e)
